package com.zw.chat.service.impl;

import com.zw.chat.domain.ChatMessage;
import com.zw.chat.domain.ChatSession;
import com.zw.chat.repository.ChatMessageRepository;
import com.zw.chat.repository.ChatSessionRepository;
import com.zw.chat.service.IChatSessionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * @author by: zyl
 * @ClassName: ChatSessionServiceImpl
 * @Description: 会话服务实现类
 * @Date: 2024/12/5 10:46
 */
@Service
public class ChatSessionServiceImpl implements IChatSessionService {

    @Autowired
    private ChatSessionRepository chatSessionRepository;

    @Autowired
    private ChatMessageRepository chatMessageRepository;

    @Override
    public ChatSession saveOrUpdateChatSession(ChatSession session) {
        return chatSessionRepository.save(session);
    }

    @Override
    public ChatSession findChatSessionById(String id) {
        return chatSessionRepository.findById(id).orElse(null);
    }

    @Override
    public void deleteChatSessionById(String id) {
        chatSessionRepository.deleteById(id);
    }

    @Override
    public List<ChatSession> queryChatSession(String userId) {
        PageRequest pageRequest = PageRequest.of(0, 10);
        pageRequest.withSort(Sort.Direction.DESC, "createTime");
        List<ChatSession> chatSessions = chatSessionRepository.queryChatSession(userId, pageRequest);
        for (ChatSession chatSession : chatSessions) {
            List<ChatMessage> chatMessages = chatMessageRepository.queryChatMessageBySessionId(chatSession.getId(), Pageable.ofSize(10));
            chatSession.setMessages(chatMessages);
        }
        return chatSessions;
    }
}
